package org.btik.light.mobile.ui.devs.arm;

import android.os.Bundle;
import android.view.*;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import org.btik.light.mobile.databinding.FragmentArmBinding;
import org.btik.light.mobile.ui.factory.DevPanel;
import org.btik.light.mobile.ui.devs.arm.handel.ArmPosHandler;
import org.btik.light.mobile.ui.devs.arm.model.ArmMo;
import org.btik.light.mobile.ui.devs.arm.model.ArmViewModel;


public class ArmFragment extends DevPanel<ArmViewModel> {
    private FragmentArmBinding bind;

    private final SeekBarShow[] progressShows = new SeekBarShow[4];

    public ArmFragment(ArmMo dev) {
        super(dev);
    }


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        model = new ViewModelProvider(this).get(ArmViewModel.class);
        bindModel();
        model.setMo(dev);
        bind = FragmentArmBinding.inflate(inflater, container, false);
        bindAction();
        return bind.getRoot();
    }

    private void bindAction() {
        int defaultVal = 50;

        TextView servoPos0 = bind.servoPos0;
        TextView servoPos1 = bind.servoPos1;
        TextView servoPos2 = bind.servoPos2;
        TextView servoPos3 = bind.servoPos3;

        SeekBar servoPosBar0 = bind.servoPosBar0;
        servoPosBar0.setOnSeekBarChangeListener(new ArmPosHandler(0, model));
        SeekBar servoPosBar1 = bind.servoPosBar1;
        servoPosBar1.setOnSeekBarChangeListener(new ArmPosHandler(1, model));
        SeekBar servoPosBar2 = bind.servoPosBar2;
        servoPosBar2.setOnSeekBarChangeListener(new ArmPosHandler(2, model));
        SeekBar servoPosBar3 = bind.servoPosBar3;
        servoPosBar3.setOnSeekBarChangeListener(new ArmPosHandler(3, model));
        progressShows[0] = new SeekBarShow(servoPos0, servoPosBar0);
        progressShows[1] = new SeekBarShow(servoPos1, servoPosBar1);
        progressShows[2] = new SeekBarShow(servoPos2, servoPosBar2);
        progressShows[3] = new SeekBarShow(servoPos3, servoPosBar3);
        model.setSetPosShow(this::updatePosShow);

        for (int i = 0; i < progressShows.length; i++) {
            int pos = model.pos(i, defaultVal);
            progressShows[i].setProgress(pos);
        }
    }

    private void updatePosShow(int index, int pos) {
        progressShows[index].setProgress(pos);
    }

    static class SeekBarShow {
        TextView textView;
        SeekBar seekBar;

        void setProgress(int progress) {
            String strVal = Integer.toString(progress);
            textView.setText(strVal);
            seekBar.setProgress(progress);
        }

        public SeekBarShow(TextView textView, SeekBar seekBar) {
            this.textView = textView;
            this.seekBar = seekBar;
        }
    }

}
